{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 八、生成对抗网络\n",
    "(Generative Adversarial Networks, GAN)\n",
    "## 8.1 基本概念\n",
    "生成对抗网络（GAN）是一种深度学习模型，它由两部分组成：生成器（Generator）和判别器（Discriminator）。生成器的目标是生成尽可能真实的数据，以欺骗判别器，而判别器的目标是尽可能准确地区分真实数据和生成的数据。\n",
    "## 8.2 关键技术\n",
    "GAN 的关键技术包括生成器和判别器。<br/>\n",
    "![GAN](../images/8-gan-network.webp)<br/>\n",
    "生成器：生成器是 GAN 的一部分，它的目标是生成尽可能真实的数据。生成器可以看作是一个映射函数，它将随机噪声映射到数据空间。<br/>\n",
    "判别器：判别器是 GAN 的另一部分，它的目标是尽可能准确地区分真实数据和生成的数据。判别器可以看作是一个二分类器。<br/>\n",
    "![GAN](../images/8-gan-network2.webp)<br/>\n",
    "GAN 的训练过程可以看作是一个二人零和博弈，生成器和判别器互相竞争，最终达到一个纳什均衡。<br/>\n",
    "## 8.3 应用领域\n",
    "GAN 广泛应用于图像生成、图像超分辨率、图像到图像的转换等领域。\n",
    "## 8.4 优点\n",
    "GAN 的主要优点是能够生成高质量、逼真的数据。\n",
    "## 8.5 缺点\n",
    "GAN 的主要缺点是训练过程可能会遇到模式崩溃和不稳定的问题。\n",
    "## 8.6 实例分析\n",
    "DCGAN、WGAN 和 CycleGAN 是一些著名的基于 GAN 的深度学习模型，它们在图像生成等任务上取得了显著的成果。\n",
    "## 8.7 手动实现\n",
    "以下是一个简单的 GAN 的 Python 实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这段代码首先定义了一个生成器类和一个判别器类，然后在每个类的 `forward` 方法中实现了前向传播过程。\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "# 定义生成器\n",
    "class Generator(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Generator, self).__init__()\n",
    "        self.main = nn.Sequential(\n",
    "            nn.Linear(100, 256),\n",
    "            nn.ReLU(True),\n",
    "            nn.Linear(256, 512),\n",
    "            nn.ReLU(True),\n",
    "            nn.Linear(512, 1024),\n",
    "            nn.ReLU(True),\n",
    "            nn.Linear(1024, 784),\n",
    "            nn.Tanh()\n",
    "        )\n",
    "\n",
    "    def forward(self, input):\n",
    "        return self.main(input)\n",
    "\n",
    "# 定义判别器\n",
    "class Discriminator(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Discriminator, self).__init__()\n",
    "        self.main = nn.Sequential(\n",
    "            nn.Linear(784, 1024),\n",
    "            nn.ReLU(True),\n",
    "            nn.Dropout(0.3),\n",
    "            nn.Linear(1024, 512),\n",
    "            nn.ReLU(True),\n",
    "            nn.Dropout(0.3),\n",
    "            nn.Linear(512, 256),\n",
    "            nn.ReLU(True),\n",
    "            nn.Dropout(0.3),\n",
    "            nn.Linear(256, 1),\n",
    "            nn.Sigmoid()\n",
    "        )\n",
    "\n",
    "    def forward(self, input):\n",
    "        return self.main(input)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
